package com.pocket.demo.core.security;

import cn.hutool.json.JSONUtil;
import com.pocket.demo.base.enums.MsgCodeEnum;
import com.pocket.demo.base.utils.ServletUtils;
import com.pocket.demo.business.service.PocketUserDetailsService;
import com.pocket.demo.core.i18n.MessageSourceService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.io.IOException;

/**
 * @author zhaozhile
 */
public class AuthenticationHandler implements AuthenticationFailureHandler, AuthenticationSuccessHandler, LogoutSuccessHandler, AuthenticationEntryPoint, SessionInformationExpiredStrategy, AccessDeniedHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationHandler.class);

    private PocketUserDetailsService userDetailsService;

    public AuthenticationHandler( PocketUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 登录认证成功处理 【demo-SpringSecurity-3.7】
     *      生成 sessionId 放置 ResponseHeader;
     *      将用户认证信息 PocketUser 存放 Redis;
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        LOGGER.debug("Request【{}】Authentication Success", request.getRequestURI());
        userDetailsService.onLoginSuccess(request, response, authentication);
    }

    // 登录认证失败处理【demo-SpringSecurity-3.8】
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){
        LOGGER.error("Request【{}】Authentication Failure Exception：{}", request.getRequestURI(), exception.getMessage(), exception);
        MsgCodeEnum msgCodeEnum;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException){
            msgCodeEnum = MsgCodeEnum.ERROR_USERNAME_PASSWORD_ERROR;
        } else if (exception instanceof LockedException){
            msgCodeEnum = MsgCodeEnum.ERROR_USER_DISABLED;
        } else {
            msgCodeEnum = MsgCodeEnum.ERROR_EXCEPTION_HAPPEN;
        }
        ServletUtils.renderString(response, JSONUtil.toJsonStr(MessageSourceService.getRestResult(msgCodeEnum, new Object[0])));
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        LOGGER.debug("Request【{}】Logout Success", request.getRequestURI());
        userDetailsService.onLogoutSuccess(request, response, authentication);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException){
        LOGGER.debug("Request【{}】Commence", request.getRequestURI());
        System.out.println(1);
    }

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event){
        System.out.println("");
        // TODO
    }

    // 授权失败处理器【demo-SpringSecurity-5.5】
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ServletUtils.renderString(response, JSONUtil.toJsonStr(MessageSourceService.getRestResult(MsgCodeEnum.ERROR_UNAUTHORIZED, new Object[0])));
    }
}
